﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json; // 引入 Newtonsoft.Json 命名空间
namespace AESUtil
{
    public class CryptItem
    {
        public string Name { get; set; }
        public string CryptText { get; set; }
        public string PlainText { get; set; }

        public string Mode { get; set; }
        public string Key { get; set; }
        public string IV { get; set; }
    }
    internal class HistoryUtil
    {
        public static void saveToFile(CryptItem item)
        {
            try
            {
                String filePath = Properties.Settings.Default.historyFileName;
                List<CryptItem> oldList;
                if (File.Exists(filePath))
                {
                    // 1. 从文件读取 JSON 字符串
                    string jsonStringFromFile = File.ReadAllText(filePath);
                    // 2. 反序列化 JSON 字符串为对象
                    oldList = JsonConvert.DeserializeObject<List<CryptItem>>(jsonStringFromFile);
                }
                else
                {
                    oldList = new List<CryptItem>();
                }


                oldList.Add(item);
                string jsonString = JsonConvert.SerializeObject(oldList, Formatting.Indented);

                // 2. 将 JSON 字符串写入文件
                File.WriteAllText(filePath, jsonString);
            }
            catch (Exception)
            {
                throw;
            }
        }
        public static List<CryptItem> getHistory()
        {
            String filePath = Properties.Settings.Default.historyFileName;
            List<CryptItem> oldList;
            if (File.Exists(filePath))
            {
                // 1. 从文件读取 JSON 字符串
                string jsonStringFromFile = File.ReadAllText(filePath);

                // 2. 反序列化 JSON 字符串为对象
                oldList = JsonConvert.DeserializeObject<List<CryptItem>>(jsonStringFromFile);
            }
            else
            {
                oldList = new List<CryptItem>();
            }
            return oldList;
        }
        public static void clearHistory()
        {
            String filePath = Properties.Settings.Default.historyFileName;
            if (File.Exists(filePath))
            {
                File.WriteAllText(filePath, "[]");
            }
        }
        public static void updateHistory(List<CryptItem> newList)
        {
            String filePath = Properties.Settings.Default.historyFileName;
            if (File.Exists(filePath))
            {
                string jsonString = JsonConvert.SerializeObject(newList, Formatting.Indented);

                File.WriteAllText(filePath, jsonString);
            }
        }
    }
}
